package wli.web.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import wli.hibernate.Roles;
import wli.hibernate.db.Category;
import wli.hibernate.db.Subject;
import wli.hibernate.util.HibernateUtil;

/**
 * Servlet implementation class VLeftServlet
 */

@WebServlet(urlPatterns = { "/vleft" }, initParams = {
		//@WebInitParam(name = "os_type", value = "windowns"),
		@WebInitParam(name = "os_type", value = "unix"),
		@WebInitParam(name = "unix_base_dir", value = "/usr/share/apache2/default-site"),
		@WebInitParam(name = "unix_file_host", value = "http://192.168.1.14/"),
		@WebInitParam(name = "win_base_dir", value = "C:\\Apache\\htdocs"),
		@WebInitParam(name = "win_file_host", value = "http://192.168.1.12/") })
public class VLeftServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	String base_dir;
	String file_host;
	String os_type;
	String dir_sepe;

	public void init(ServletConfig config) throws ServletException {
		os_type = config.getInitParameter("os_type");
		if (os_type.equals("windowns")) {
			dir_sepe = "\\";
			base_dir = config.getInitParameter("win_base_dir");
			file_host = config.getInitParameter("win_file_host");
		}
		if (os_type.equals("unix")) {
			dir_sepe = "/";
			base_dir = config.getInitParameter("unix_base_dir");
			file_host = config.getInitParameter("unix_file_host");
		}
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(true);
		PrintWriter out = response.getWriter();
		String username = request.getRemoteUser();
		if (username == null) {
			username = "guest";
		}

		/**
		 * this section will save subject
		 */

		out.println("<table bgcolor=#EEEEEE>");
		out.println("<tr>");
		out.println("<td></td><td>");

		if (request.getParameter("add_subject") != null
				&& request.getParameter("subject_name") != null
				&& request.getParameter("subject_name").length() > 0
				&& request.getParameter("add_subject_form_id") != null
				&& request.getParameter("add_subject_form_id").equals(
						session.getAttribute("ADD_SUBJECT_FORM_ID").toString())) {
			if (getTotalSubject(username) < 100) {
				if (addSubject(getNextSubjectId() + 1,
						request.getParameter("vcid"),
						request.getParameter("subject_name"), username) > 0) {
					session.setAttribute("ADD_SUBJECT_FORM_ID", 100);
					request.setAttribute("vleft_main", "add_subject_ok");
				}
			} else {
				request.setAttribute("vleft_main", "add_subject_over_limit");
			}
		}

		String new_subject = request.getParameter("new_subject");
		if (new_subject != null && new_subject.length() > 0
				&& request.getParameter("add_subject") != null
				&& request.getParameter("add_subject").equals("ADD")
				&& request.getRemoteUser() != null) {

			request.setAttribute("vleft_main", "add_subject");
			session.setAttribute("ADD_SUBJECT_FORM_ID",
					System.currentTimeMillis());
		} else {
			if (request.getParameter("vcid") != null) {
				out.println("<form action=members>");
				out.println("<TABLE>");
				out.println("<TR><TD><input type=text name=new_subject size=10 maxsize=20></TD>");
				out.println("<TD><input type=submit name=add_subject value=ADD></TD>");
				out.println("</TR>");
				out.println("</TABLE>");
				out.println("<input type=hidden name=vcid value="
						+ request.getParameter("vcid") + ">");
				out.println("<input type=hidden name=vcname value="
						+ request.getParameter("vcname") + ">");
				out.println("</form>");
			}
		}

		out.println("</td>");
		out.println("</tr>");
		/**
		 * List all subject
		 */

		ArrayList alist = (ArrayList) getSubjectList(username,
				request.getParameter("vcid"));
		Iterator<Subject> its = alist.iterator();
		Subject sub = null;
		while (its.hasNext()) {
			sub = (Subject) its.next();
			out.println("<tr><td>&spades;</td><td><a href=?vcid="+sub.getCategoryId()+"&vsid="+sub.getSubject_id()+"&vcsid="+sub.getCategoryId()+"-"+sub.getSubject_id()+">" + sub.getName() + "</a></td></tr>");
		}

		out.println("</table>");
	}

	private int getTotalSubject(String username) {
		Session hsession = null;
		Transaction transaction = null;
		Subject subj = null;
		List<Subject> clist = new ArrayList<Subject>();
		try {

			hsession = HibernateUtil.getSessionFactory().openSession();
			Criteria criteria = hsession.createCriteria(Subject.class);
			clist = criteria.add(Restrictions.eq("owner", username)).list();
			// clist = criteria.list();
			// Collections.sort(flist);

		} catch (HibernateException e) {

		}
		return clist.size();
	}

	private int getTotalSubject() {
		Session hsession = null;
		Transaction transaction = null;
		Subject subj = null;
		List<Subject> clist = new ArrayList<Subject>();
		try {

			hsession = HibernateUtil.getSessionFactory().openSession();
			Criteria criteria = hsession.createCriteria(Subject.class);
			// clist = criteria.add(Restrictions.eq("owner", username)).list();
			clist = criteria.list();
			// Collections.sort(flist);

		} catch (HibernateException e) {

		}
		return clist.size();
	}

	private int getNextSubjectId() {
		Session hsession = null;
		Transaction transaction = null;
		Subject subject = null;
		List<Subject> slist = new ArrayList<Subject>();
		try {

			hsession = HibernateUtil.getSessionFactory().openSession();
			Criteria criteria = hsession.createCriteria(Subject.class);
			slist = criteria.list();
			// clist = criteria.list();
			//Collections.sort(slist);

			return (slist.get(0)).getSubject_id();

		} catch (HibernateException e) {

		}
		return slist.size();
	}
	
	private int addSubject(int sub_id, String category_id, String name,
			String owner) {

		Session hsession = null;
		Transaction transaction = null;

		try {
			hsession = HibernateUtil.getSessionFactory().openSession();

			Subject subject = new Subject();
			subject.setSubject_id(sub_id);
			subject.setName(name);
			subject.setOwner(owner);
			subject.setManager("wli");
			subject.setCategoryId(Integer.parseInt(category_id));

			subject.setDate_create(new java.sql.Date(System.currentTimeMillis()));

			hsession = HibernateUtil.getSessionFactory().openSession();
			transaction = hsession.beginTransaction();

			hsession.save(subject);
			transaction.commit();
			return 1;

		} catch (HibernateException e) {
			transaction.rollback();
			e.printStackTrace();
		} finally {
			hsession.close();
		}
		return -1;
	}

	private List<Subject> getSubjectList(String username) {
		Session hsession = null;
		Transaction transaction = null;
		Subject sub = null;
		List<Subject> slist = new ArrayList<Subject>();
		try {

			hsession = HibernateUtil.getSessionFactory().openSession();
			Criteria criteria = hsession.createCriteria(Subject.class);
			slist = criteria.add(Restrictions.eq("owner", username)).list();
			// clist = criteria.list();
			// Collections.sort(flist);
			Iterator<Subject> its = slist.iterator();
			String apace = null;
			while (its.hasNext()) {
				sub = (Subject) its.next();
				System.out.println("subject name=" + sub.getName());
			}
		} catch (HibernateException e) {

		}
		return slist;
	}

	private List<Subject> getSubjectList(String username, String category_id) {
		if (category_id == null) {
			category_id = "0";
		}
		Session hsession = null;
		Transaction transaction = null;
		Subject sub = null;
		List<Subject> slist = new ArrayList<Subject>();
		try {

			hsession = HibernateUtil.getSessionFactory().openSession();
			Criteria criteria = hsession.createCriteria(Subject.class);
			slist = criteria
					.add(Restrictions.eq("owner", username))
					.add(Restrictions.eq("categoryId",
							Integer.parseInt(category_id))).list();
			// Collections.sort(flist);
			Iterator<Subject> its = slist.iterator();
			String apace = null;
			while (its.hasNext()) {
				sub = (Subject) its.next();
			}
		} catch (HibernateException e) {

		}
		return slist;
	}
}
